package com.jielihaofeng.nettyadvance.chat.server.handler;

import com.jielihaofeng.nettyadvance.chat.message.GroupCreateRequestMessage;
import com.jielihaofeng.nettyadvance.chat.message.GroupCreateResponseMessage;
import com.jielihaofeng.nettyadvance.chat.server.session.Group;
import com.jielihaofeng.nettyadvance.chat.server.session.GroupSession;
import com.jielihaofeng.nettyadvance.chat.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

/**
 * @author Johnnie Wind
 * @description 群组创建消息处理器
 * @date 2021/11/18 15:02
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage message) throws Exception {
        // 群组名称
        String groupName = message.getGroupName();
        // 群组成员
        Set<String> members = message.getMembers();

        // 群管理器
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, members);

        // 群不存在
        if (group == null) {
            ctx.writeAndFlush(new GroupCreateResponseMessage(true, groupName + "群聊创建成功"));
            // 发送拉群信息
            List<Channel> channels = groupSession.getMembersChannel(groupName);
            channels.stream().forEach(channel -> channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入群聊：" + groupName)));
        }
        // 群已存在
        else {
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, groupName + "群聊已存在"));
        }
    }
}
